const projects = [
  {
    img: '1.png',
    h4: 'Form Validation',
    p: 'Intro to DOM & events',
    href: './form-validation',
  },
  {
    img: '2.png',
    h4: 'Exchange Rate Calculator',
    p: 'Fetch API, JSON',
    href: './exchange-rate',
  },
  {
    img: '3.png',
    h4: 'Music Player',
    p: 'UI/Animation, Audio API',
    href: './music-player',
  },
  {
    img: '4.png',
    h4: 'Custom Video Player',
    p: 'HTML5 Video API',
    href: './custom-video-player',
  },
  {
    img: '5.png',
    h4: 'New Year Countdown',
    p: 'DOM, Events, CSS, Time',
    href: './new-year-countdown',
  },
  {
    img: '6.png',
    h4: 'Speak Number Guess',
    p: 'Speech Recognition API',
    href: './speak-number-guess',
  },  
  {
    img: '7.png',
    h4: 'Breakout!',
    p: 'HTML5 Canvas API',
    href: './breakout-game',
  },
  {
    img: '8.png',
    h4: '3D Transform',
    p: 'CSS, event',
    href: './3d-transform',
  },
]

const section = document.getElementById('projects')

for (let index in projects) {
  const i = document.createElement('div')
  i.innerHTML = `  
    <img src="${projects[index].img}" alt="" />
    <div class="content">
      <h4>${projects[index].h4}</h4>
      <p>${projects[index].p}</p>
      <a href="${projects[index].href}" target="_blank" class="btn">
        Live Demo
      </a>
    </div>
  `
  section.appendChild(i)

  // pc上
  if (!/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
    document.querySelectorAll('.content').forEach((i) => {
      i.style.top = '100%'
      i.style.opacity = 0.9
    })

    i.addEventListener('mouseenter', (e) => {
      const dir = getDir(e, i)
      setTransition(i.getElementsByClassName('content')[0], dir)
    })
    
    i.addEventListener('mouseleave', (e) => {
      const dir = getDir(e, i)
      setTimeout(() => {
        i.getElementsByClassName('content')[0].style.top = initPos[dir].top
        i.getElementsByClassName('content')[0].style.left = initPos[dir].left
      })
    })
  }
}

function getDir(ev, el) {
  const { width, height } = el.getBoundingClientRect()

  const x = (ev.offsetX - width / 2) * (width > height ? height / width : 1)
  const y = (ev.offsetY - height / 2) * (height > width ? width / height : 1)

  const deg = (Math.atan2(y, x) / Math.PI) * 180

  const dir = (Math.round((deg + 180) / 90) + 3) % 4

  return dir // 上0 右1 下2 左3
}

const initPos = [
  { left: '0', top: '-100%' },
  { left: '100%', top: '0' },
  { left: '0', top: '100%' },
  { left: '-100%', top: '0' },
]

function setTransition(el, dir) {
  el.style.transition = ''
  el.style.top = initPos[dir].top
  el.style.left = initPos[dir].left

  setTimeout(() => {
    el.style.transition = '.3s'
    el.style.top = '0'
    el.style.left = '0'
  })
}
